// 主题管理工具
export class ThemeManager {
  constructor() {
    this.root = document.documentElement
    this.loadSavedSettings()
  }

  // 加载保存的设置
  loadSavedSettings() {
    try {
      const savedSettings = localStorage.getItem('app-settings')
      if (savedSettings) {
        const settings = JSON.parse(savedSettings)
        this.applyTheme(settings)
      }
    } catch (error) {
      console.error('加载主题设置失败:', error)
    }
  }

  // 应用主题
  applyTheme(settings) {
    if (!settings) return

    // 应用主色调
    if (settings.primaryColor) {
      this.setPrimaryColor(settings.primaryColor)
    }

    // 应用主题模式
    if (settings.theme) {
      this.setThemeMode(settings.theme)
    }

    // 应用字体大小
    if (settings.fontSize) {
      this.setFontSize(settings.fontSize)
    }

    // 应用紧凑模式
    if (settings.compactMode !== undefined) {
      this.setCompactMode(settings.compactMode)
    }

    // 应用动画设置
    if (settings.animations !== undefined) {
      this.setAnimations(settings.animations)
    }
  }

  // 设置主色调
  setPrimaryColor(color) {
    // 生成主题色的各种变体
    const colors = this.generateColorVariants(color)
    
    // 应用到CSS变量
    Object.keys(colors).forEach(key => {
      this.root.style.setProperty(key, colors[key])
    })

    // 更新Element Plus主题色
    this.root.style.setProperty('--el-color-primary', color)
    
    // 生成Element Plus的主题色变体
    for (let i = 1; i <= 9; i++) {
      this.root.style.setProperty(
        `--el-color-primary-light-${i}`,
        this.lightenColor(color, i * 0.1)
      )
    }
    
    this.root.style.setProperty(
      '--el-color-primary-dark-2',
      this.darkenColor(color, 0.2)
    )
  }

  // 设置主题模式
  setThemeMode(mode) {
    const isDark = mode === 'dark' || (mode === 'auto' && this.isSystemDark())
    
    if (isDark) {
      this.root.classList.add('dark')
      document.body.classList.add('dark-theme')
    } else {
      this.root.classList.remove('dark')
      document.body.classList.remove('dark-theme')
    }
  }

  // 设置字体大小
  setFontSize(size) {
    const fontSizeMap = {
      small: '12px',
      medium: '14px',
      large: '16px'
    }
    this.root.style.setProperty('--el-font-size-base', fontSizeMap[size] || '14px')
  }

  // 设置紧凑模式
  setCompactMode(compact) {
    if (compact) {
      this.root.style.setProperty('--el-component-size', 'small')
      document.body.classList.add('compact-mode')
    } else {
      this.root.style.setProperty('--el-component-size', 'default')
      document.body.classList.remove('compact-mode')
    }
  }

  // 设置动画
  setAnimations(enabled) {
    if (enabled) {
      document.body.classList.remove('no-animations')
    } else {
      document.body.classList.add('no-animations')
    }
  }

  // 生成颜色变体
  generateColorVariants(baseColor) {
    return {
      '--theme-primary': baseColor,
      '--theme-primary-light': this.lightenColor(baseColor, 0.2),
      '--theme-primary-lighter': this.lightenColor(baseColor, 0.4),
      '--theme-primary-dark': this.darkenColor(baseColor, 0.2),
      '--theme-primary-darker': this.darkenColor(baseColor, 0.4),
      '--theme-primary-alpha-10': this.addAlpha(baseColor, 0.1),
      '--theme-primary-alpha-20': this.addAlpha(baseColor, 0.2),
      '--theme-primary-alpha-30': this.addAlpha(baseColor, 0.3),
    }
  }

  // 颜色变亮
  lightenColor(color, amount) {
    const rgb = this.hexToRgb(color)
    if (!rgb) return color

    const r = Math.min(255, Math.round(rgb.r + (255 - rgb.r) * amount))
    const g = Math.min(255, Math.round(rgb.g + (255 - rgb.g) * amount))
    const b = Math.min(255, Math.round(rgb.b + (255 - rgb.b) * amount))

    return `rgb(${r}, ${g}, ${b})`
  }

  // 颜色变暗
  darkenColor(color, amount) {
    const rgb = this.hexToRgb(color)
    if (!rgb) return color

    const r = Math.max(0, Math.round(rgb.r * (1 - amount)))
    const g = Math.max(0, Math.round(rgb.g * (1 - amount)))
    const b = Math.max(0, Math.round(rgb.b * (1 - amount)))

    return `rgb(${r}, ${g}, ${b})`
  }

  // 添加透明度
  addAlpha(color, alpha) {
    const rgb = this.hexToRgb(color)
    if (!rgb) return color

    return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`
  }

  // 十六进制转RGB
  hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  }

  // 检查系统是否为深色主题
  isSystemDark() {
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
  }

  // 监听系统主题变化
  watchSystemTheme(callback) {
    if (window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      mediaQuery.addEventListener('change', callback)
      return () => mediaQuery.removeEventListener('change', callback)
    }
    return () => {}
  }
}

// 创建全局主题管理器实例
export const themeManager = new ThemeManager()

// 导出便捷方法
export const applyTheme = (settings) => themeManager.applyTheme(settings)
export const setPrimaryColor = (color) => themeManager.setPrimaryColor(color)
export const setThemeMode = (mode) => themeManager.setThemeMode(mode)
